package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.PrizeHistoryhorizontalAdapter;
import com.lottery.ruok.lottrey.adapter.PrizePagerAdapter;
import com.lottery.ruok.lottrey.adapter.fragmentManager.PrizeListPagerFragmentManager;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.ListToTop;
import com.lottery.ruok.lottrey.eventbusObject.PrizePushInfo;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.eventbusObject.Tabs;
import com.lottery.ruok.lottrey.interfaces.PrizeNumberListViewLoadMoreListener;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.LotteryStatOneRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.LotteryStatOneResponse;
import com.lottery.ruok.lottrey.ui.MyScrollView;
import com.lottery.ruok.lottrey.ui.ShapeIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.observers.DisposableObserver;
import library.CardScaleHelper;
import ui.AreaCircle;
import utils.Utils;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;

/*
 * 开奖记录item详情页
 * */

public class PrizeListActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.type)
    LinearLayout type;
    @BindView(R.id.horizontal_list)
    RecyclerView horizontalList;
    PrizeHistoryhorizontalAdapter mAdapter_horizontal;
    @BindView(R.id.lottery_time)
    TextView lotteryTime;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.custom_indicator)
    ShapeIndicatorView customIndicator;
    @BindView(R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.vp_view)
    ViewPager vpView;
    @BindView(R.id.scrollView)
    MyScrollView scrollView;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tips)
    TextView tips;
    @BindView(R.id.gotoLotteryButton)
    RelativeLayout gotoLotteryButton;
    @BindView(R.id.anim_view)
    LottieAnimationView animView;
    @BindView(R.id.anim_view_open)
    LottieAnimationView animViewOpen;
    @BindView(R.id.tops)
    ImageView tops;
    @BindView(R.id.goto_top)
    public ImageView gotoTop;
    private String ANALYTIC_VERSION = "1.0";

    private Timer timer = new Timer();
    private TimerTask task;
    int duringTime = 0;
    int periodTime = 0;

    public LotteryStatOneResponse lotteryStatOneResponses;

    private boolean canScroll = false;
    public String currentCategory;
    public String currentDate;
    private boolean isFromDetail;//来自购彩页面
    private boolean isFirstIn = true;//是否第一次进入

    private ArrayList<LotteryStatOneResponse.ItemListBeans> itemListBeanArrayList = new ArrayList<>();

    private String mCurrentCode;
    private int mCurrentItemClass;

    private PrizePagerAdapter mAdapter;
    private int mPosition;
    private int mDefaultIndex = 0;
    private int mDefaultSize = 50;
    private Runnable scrollRunnable;
    private Runnable horizontalRunnable;
    private long lastBackTime = 0;
    private long currentBackTime = 0;

    @Override
    protected void onDestroy() {
        PrizeListPagerFragmentManager.clear();
        super.onDestroy();

        EventBus.getDefault().unregister(this);

        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
        if (scrollRunnable != null) {
            scrollView.removeCallbacks(scrollRunnable);
        }
        if (horizontalRunnable != null) {
            horizontalList.removeCallbacks(horizontalRunnable);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrizePushInfo event) {
        if (event.getCode() != null) {
            if (currentCategory != null) {
                if (("ct" + event.getCode()).equals(currentCategory) || event.getCode().equals(currentCategory)) {
                    getPrizeCondition(currentCategory, currentDate, mPosition);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartPrzePush event) {
        getPrizeCondition(currentCategory, currentDate, mPosition);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prize_list);

        EventBus.getDefault().register(this);

        ButterKnife.bind(this);

        init();

    }


    /**
     * 获取中奖状态
     */
    private void getPrizeCondition(final String code, final String date, final int position) {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(LotteryStatOneRequest.class).getResult(code, date, mDefaultIndex, mDefaultSize)
                .compose(RxHelper.<LotteryStatOneResponse>handleResultReConnection())
                .subscribeWith(new RxSubscribe<LotteryStatOneResponse>(this) {
                    @Override
                    protected void _onNext(LotteryStatOneResponse lotteryStatOneResponse) {
                        lotteryStatOneResponses = lotteryStatOneResponse;

                        duringTime = lotteryStatOneResponse.getTime();
                        periodTime = lotteryStatOneResponse.getInterval();
//                        PrizeListPagerFragmentManager.clear();
                        PrizeListPagerFragmentManager.setData(lotteryStatOneResponse);
                        setTopCondition(mPosition);

                        if (lotteryStatOneResponses.getOpenning() == 1) {
                            //设置开奖相关的东西，如小球等
                            animView.setVisibility(View.GONE);
                            animView.pauseAnimation();
                            animViewOpen.setVisibility(View.VISIBLE);
                            animViewOpen.resumeAnimation();

                            tips.setVisibility(View.GONE);
                            time.setVisibility(View.GONE);
                            title.setText("正在开奖");
                        } else {
                            //设置开奖相关的东西，如小球等
                            animView.setVisibility(View.VISIBLE);
                            animView.resumeAnimation();
                            animViewOpen.setVisibility(View.GONE);
                            animViewOpen.pauseAnimation();
                            tips.setVisibility(View.VISIBLE);
                            time.setVisibility(View.VISIBLE);
                            title.setText("购彩");
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void setTopCondition(int position) {
        View view = horizontalList.getLayoutManager().findViewByPosition(position);
        if (view != null) {
            if (lotteryStatOneResponses.getOpenning() == 0) {
                TextView no = view.findViewById(R.id.no);
                no.setText(lotteryStatOneResponses.getIssue_no() + "期开奖");
                TextView open = view.findViewById(R.id.open);
                open.setVisibility(View.VISIBLE);
                TextView lottery_name = view.findViewById(R.id.lottery_name);
                if (lottery_name.getText().toString().equals("福彩3D") || lottery_name.getText().toString().equals("排列三")) {//福彩3D和排列三是特殊情况
                    open.setText("每天" + lotteryStatOneResponses.getOpen_time() + "开奖");
                    type.setVisibility(View.INVISIBLE);

                } else {
                    type.setVisibility(View.VISIBLE);
                    open.setText(String.format("已开%s期，剩余%s期", lotteryStatOneResponses.getHad_open_num(), lotteryStatOneResponses.getRemain_num()));
                }

                TextView prize_detail = view.findViewById(R.id.prize_detail);
                prize_detail.setVisibility(View.VISIBLE);
                if (lotteryStatOneResponses.getText() != null && !lotteryStatOneResponses.getText().equals("")) {
                    prize_detail.setText(lotteryStatOneResponses.getText());
                    prize_detail.setVisibility(View.VISIBLE);
                } else {
                    prize_detail.setVisibility(View.GONE);
                }

                TextView prizing = view.findViewById(R.id.prizing);
                prizing.setVisibility(View.GONE);

                LinearLayout container = view.findViewById(R.id.container);
                container.setVisibility(View.VISIBLE);
                container.removeAllViews();
                String[] temp = lotteryStatOneResponses.getPrize_num().split(",");
                if (temp != null) {
                    String code = lotteryStatOneResponses.getItem_code();
                    if("ahk3".equals(code)||"jiangsuk3".equals(code)||Common.isK3(code)){
                        for (String s : temp) {
                            int num = Integer.parseInt(s);
                            ImageView imageView = new ImageView(this);
                            imageView.setImageResource(Common.getDiceDrawable(num));
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 20), Utils.dip2px(this, 20));
                            layoutParams.rightMargin = Utils.dip2px(this, 6);
                            imageView.setLayoutParams(layoutParams);
                            container.addView(imageView);
                        }
                    }else {
                        for (String s : temp) {
                            AreaCircle areaCircle = new AreaCircle(PrizeListActivity.this);
                            Common.setBallBackground(areaCircle, s, mCurrentCode);
                            areaCircle.setText(s);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(PrizeListActivity.this, 20), Utils.dip2px(PrizeListActivity.this, 20));
                            layoutParams.rightMargin = Utils.dip2px(PrizeListActivity.this, 6);
                            areaCircle.setLayoutParams(layoutParams);
                            container.addView(areaCircle);
                        }
                    }
                }
            } else {
                setTopPrizeOpen(view);
            }
        }
    }

    private void setTopPrizeOpen(View view) {
        if (view != null) {
            TextView no = view.findViewById(R.id.no);
            no.setText(lotteryStatOneResponses.getNo() + "期");

            TextView open = view.findViewById(R.id.open);
            open.setVisibility(View.GONE);

            LinearLayout container = view.findViewById(R.id.container);
            container.setVisibility(View.INVISIBLE);

            TextView prize_detail = view.findViewById(R.id.prize_detail);
            prize_detail.setVisibility(View.GONE);

            TextView prizing = view.findViewById(R.id.prizing);
            prizing.setVisibility(View.VISIBLE);
        }
    }

    private void getList(final String code, final String date, final int position, int index, int size) {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(LotteryStatOneRequest.class).getResult(code, date, index, size)
                .compose(RxHelper.<LotteryStatOneResponse>handleResult())
                .subscribeWith(new RxSubscribe<LotteryStatOneResponse>(this) {
                    @Override
                    protected void _onNext(LotteryStatOneResponse lotteryStatOneResponse) {
                        mAdapter_horizontal.setDatas(lotteryStatOneResponse);
                        mCurrentCode = lotteryStatOneResponse.getItem_code();
                        mCurrentItemClass = lotteryStatOneResponse.getItem_class();

                        currentCategory = lotteryStatOneResponse.getItem_code();
                        lotteryStatOneResponses = lotteryStatOneResponse;

                        duringTime = lotteryStatOneResponse.getTime();
                        periodTime = lotteryStatOneResponse.getInterval();
                        PrizeListPagerFragmentManager.clear();
                        PrizeListPagerFragmentManager.setData(lotteryStatOneResponse);
                        if (lotteryStatOneResponse.getOnetab() != null) {
                            String[] titles = lotteryStatOneResponse.getOnetab().split(",");
                            boolean hasNumberDistribute = false;
//                            for (int i = 0; i < titles.length; i++) {
//                                switch (i) {
//                                    case 0: {
//                                        PrizeNumberFragment categoryFragment = new PrizeNumberFragment();
//                                        mViewList.add(categoryFragment);
//                                        break;
//                                    }
//                                    case 1: {
//                                        TwoSidedStatisticsFragment categoryFragment = new TwoSidedStatisticsFragment();
//                                        mViewList.add(categoryFragment);
//                                        break;
//                                    }
//                                    case 2: {
//                                        LongDragonFragment categoryFragment = new LongDragonFragment();
//                                        mViewList.add(categoryFragment);
//                                        break;
//                                    }
//                                    case 3: {
//                                        hasNumberDistribute = true;
//                                        DistributionFragment categoryFragment = new DistributionFragment();
//                                        mViewList.add(categoryFragment);
//                                        break;
//                                    }
//                                }
//                            }

                            mAdapter = new PrizePagerAdapter(getSupportFragmentManager());//给ViewPager设置适配器
//                            vpView.removeAllViews();
                            vpView.setAdapter(mAdapter);

                            if (mAdapter.getCount() > 0) {
                                vpView.setOffscreenPageLimit(mAdapter.getCount());
                            }
                            tabLayout.setTabsFromPagerAdapter(mAdapter);
                            tabLayout.getTabAt(0).select();

                            if (titles.length == 1) {
                                customIndicator.setVisibility(View.GONE);
                            } else {
                                customIndicator.setVisibility(View.VISIBLE);
                            }
                            customIndicator.setupWithTabLayout(tabLayout);
                            customIndicator.setupWithViewPager(vpView);

                            if (isFromDetail && hasNumberDistribute) {
                                vpView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        vpView.setCurrentItem(mAdapter.getCount() - 1);
                                    }
                                });
                            }
                        }

                        mPosition = position;
                        if (position != -1) {//横向轮播直接刷新会出现缩小的bug，先用这种方法
                            setTopCondition(mPosition);
                        }

                        if (lotteryStatOneResponses.getOpenning() == 1) {
                            //设置开奖相关的东西，如小球等
                            animView.setVisibility(View.GONE);
                            animView.pauseAnimation();
                            animViewOpen.setVisibility(View.VISIBLE);
                            animViewOpen.resumeAnimation();
                            tips.setVisibility(View.GONE);
                            time.setVisibility(View.GONE);
                            title.setText("正在开奖");
                        } else {
                            //设置开奖相关的东西，如小球等
                            animView.setVisibility(View.VISIBLE);
                            animView.resumeAnimation();
                            animViewOpen.setVisibility(View.GONE);
                            animViewOpen.pauseAnimation();
                            tips.setVisibility(View.VISIBLE);
                            time.setVisibility(View.VISIBLE);
                            title.setText("购彩");
                        }

                        if (isFromDetail) {
                            scrollRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    isFromDetail = false;
                                    scrollView.scrollTo(0, scrollView.getBottom());
                                }
                            };
                            scrollView.postDelayed(scrollRunnable, 50);
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void init() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) vpView.getLayoutParams();
        layoutParams.height = Utils.getWindowDisplay(this).heightPixels - Utils.dip2px(getApplicationContext(), 115);
        vpView.setLayoutParams(layoutParams);

        tops.setAlpha(0f);

        isFromDetail = getIntent().getBooleanExtra("isFromDetail", false);

        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(LotteryStatOneRequest.class).getResult(getIntent().getStringExtra("code"), null, mDefaultIndex, mDefaultSize)
                .compose(RxHelper.<LotteryStatOneResponse>handleResult())
                .subscribeWith(new RxSubscribe<LotteryStatOneResponse>(this) {
                    @Override
                    protected void _onNext(final LotteryStatOneResponse lotteryStatOneResponse) {
                        lotteryStatOneResponses = lotteryStatOneResponse;
                        mCurrentCode = lotteryStatOneResponse.getItem_code();
                        mCurrentItemClass = lotteryStatOneResponse.getItem_class();

                        for (LotteryStatOneResponse.ItemListBean itemListBeen : lotteryStatOneResponse.getItem_list()) {
                            for (LotteryStatOneResponse.ItemListBean.ItemsBean l : itemListBeen.getItems()) {
                                LotteryStatOneResponse.ItemListBeans t = new LotteryStatOneResponse.ItemListBeans();
                                t.setCode(l.getCode());
                                t.setNameX(l.getNameX());
                                itemListBeanArrayList.add(t);
                            }
                        }

                        currentDate = lotteryStatOneResponse.getServer_time();
                        lotteryTime.setText(lotteryStatOneResponse.getServer_time());

                        itemListBeanArrayList.get(0).isLeft = true;
                        itemListBeanArrayList.get(itemListBeanArrayList.size() - 1).isRight = true;

                        mAdapter_horizontal = new PrizeHistoryhorizontalAdapter(PrizeListActivity.this, itemListBeanArrayList, lotteryStatOneResponses);
                        horizontalList.setHasFixedSize(true);
                        final LinearLayoutManager layoutManager = new LinearLayoutManager(PrizeListActivity.this, LinearLayoutManager.HORIZONTAL, false);
                        horizontalList.setLayoutManager(layoutManager);
                        horizontalList.setAdapter(mAdapter_horizontal);

                        DividerItemDecoration itemDecorator = new DividerItemDecoration(PrizeListActivity.this, DividerItemDecoration.HORIZONTAL);
                        itemDecorator.setDrawable(ContextCompat.getDrawable(PrizeListActivity.this, R.drawable.shape_divider_10));
                        horizontalList.addItemDecoration(itemDecorator);

                        // mRecyclerView绑定scale效果
                        CardScaleHelper mCardScaleHelper = new CardScaleHelper();
                        mCardScaleHelper.attachToRecyclerView(horizontalList);
                        mCardScaleHelper.setScrollListener(new CardScaleHelper.ScrollListener() {
                            @Override
                            public void onScrollStateChange(int newState) {
                                if (newState == SCROLL_STATE_IDLE) {
                                    int result = layoutManager.findFirstCompletelyVisibleItemPosition();
                                    currentBackTime = System.currentTimeMillis();
                                    if (result != -1 && currentBackTime - lastBackTime > 500 && !itemListBeanArrayList.get(result).getCode().equals(currentCategory)) {//500ms之内只能进来一次
                                        getList(itemListBeanArrayList.get(result).getCode(), currentDate, result, mDefaultIndex, mDefaultSize);
                                        lastBackTime = currentBackTime;
                                    }
                                }
                            }
                        });

                        task = new TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (duringTime == 0) {
                                            //设置开奖相关的东西，如小球等
                                            animView.setVisibility(View.GONE);
                                            animView.pauseAnimation();
                                            animViewOpen.setVisibility(View.VISIBLE);
                                            animViewOpen.resumeAnimation();
                                            tips.setVisibility(View.GONE);
                                            time.setVisibility(View.GONE);
                                            title.setText("正在开奖");

                                            View view = horizontalList.getLayoutManager().findViewByPosition(mPosition);
                                            setTopPrizeOpen(view);

                                            duringTime = periodTime;
                                        } else {
                                            duringTime--;
                                        }

                                        time.setText(Utils.getCountTimeByLong(duringTime * 1000));
                                    }
                                });
                            }
                        };
                        timer.schedule(task, 1000, 1000);

                        horizontalList.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                scrollToPosition(getIntent().getStringExtra("code"));

                            }
                        }, 50);
                        if (isFirstIn && itemListBeanArrayList.get(0).getCode().equals(getIntent().getStringExtra("code"))) {//如果刚进来的第一个就是我选择的那个彩种，横向列表不需要移动就可以加载
                            getList(itemListBeanArrayList.get(0).getCode(), null, 0, mDefaultIndex, mDefaultSize);
                        }
                        isFirstIn = false;
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
        disposables.add(disposableObserver);

        scrollView.setScrollViewListener(new MyScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
                float h = y * 1.0f - Utils.dip2px(getApplicationContext(), 65);
                if (h >= 0) {
                    tops.setAlpha(h / Utils.dip2px(getApplicationContext(), 65));
                } else if (h < 0) {
                    tops.setAlpha(0f);
                }

                View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
                int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
                if (diff == 0) {// if diff is zero, then the bottom has been reached
                    Tabs tabs = new Tabs();
                    tabs.setCanListScroll(true);// 设置scrollview不能滚动，listview可以滚动
                    EventBus.getDefault().post(tabs);
                    canScroll = true;
                } else {
                    if (canScroll) {
                        canScroll = false;
                        Tabs tabs = new Tabs();
                        tabs.setCanListScroll(false);
                        EventBus.getDefault().post(tabs);
                    }
                }
            }
        });
    }

    @OnClick({R.id.back, R.id.type, R.id.gotoLotteryButton, R.id.goto_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.type:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_numdistributing_select_date");

                Intent intent = new Intent(PrizeListActivity.this, ChooseDateActivity.class);
                startActivityForResult(intent, 101);
                overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                break;
            case R.id.gotoLotteryButton:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_numdistributing_buy_jump");

                gotoLotteryDetailActivity(mCurrentCode, mCurrentItemClass);
                break;
            case R.id.goto_top:
                EventBus.getDefault().post(new ListToTop());
                break;
        }
    }

    private void scrollToPosition(String code) {
        int pos = 0;
        for (int i = 0; i < itemListBeanArrayList.size(); i++) {
            if (itemListBeanArrayList.get(i).getCode().equals(code)) {
                pos = i;
                break;
            }
        }
        final int y = pos;
        horizontalRunnable = new Runnable() {
            @Override
            public void run() {
                horizontalList.smoothScrollToPosition(y);
            }
        };
        horizontalList.postDelayed(horizontalRunnable, 50);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == ChooseLotteryActivity.REPONSE_CODE) {
            String code = data.getStringExtra("code");
            if (!Utils.isEmpty(code)) {
                if ("jslhc".equals(code)||"js10flhc".equals(code)) {
                    //跳转到极速六合彩走势
                    LiuhecaiPrizeActivity.startActivity(this, code, false);
                    return;
                } else if ("xglhc".equals(code)) {
                    //跳转到香港六合彩走势
                    LiuhecaiPrizeActivity.startActivity(this, code, false);
                    return;
                }
                scrollToPosition(code);
            }
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            String date = data.getStringExtra("date").split(" ")[0];
            lotteryTime.setText(date);
            currentDate = date;
            getList(currentCategory, date, -1, mDefaultIndex, mDefaultSize);
        }
    }

}